<template>
  <div class="login">
    <el-row style="margin-top: 160px;z-index: 1;">
      <el-col :offset="5" :span="6" style="margin-top: 60px">
        <h1 style="color: white">欢迎使用饮料自动贩卖机后台系统（默认账户密码为：admin）</h1>
      </el-col>
      <el-col :offset="2" :span="6">
        <!-- <el-card class="login-box" v-loading="$store.state.loading" element-loading-background="rgba(0, 0, 0, 0.8)"> -->
        <el-card class="login-box" element-loading-background="rgba(0, 0, 0, 0.8)">
          <el-form  :model="userForm" :rules="rules" ref="userForm">
            <h1 class="title">账号登入</h1>
            <el-form-item prop="userName">
              <el-input type="text" v-model="userForm.userName" auto-complete="off" placeholder="请输入用户名..."
                        suffix-icon="el-icon-bell"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input type="password" v-model="userForm.password" auto-complete="off" placeholder="请输入密码..."
                        suffix-icon="el-icon-edit"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="judgeLogin('userForm')" style="width:100%">登录</el-button>
            </el-form-item>
          </el-form>
          <el-row style="font-size: small; color: grey">
            <el-col :offset="6" :span="5"><a>忘记密码</a></el-col>
            <el-col :offset="1" :span="5"><a>忘记会员名</a></el-col>
            <el-col :offset="1" :span="5"><a @click="registerFormVisible = true">免费注册</a></el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="注册" :visible.sync="registerFormVisible" :modal="registerForModal" width="30%">
      <el-form :model="registerForm" :rules="rules" ref="registerForm">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="userName">
          <el-input v-model="registerForm.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" :label-width="formLabelWidth" prop="password">
          <el-input type="password" v-model="registerForm.password" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="registerFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="judgeRegister('registerForm')">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>
<style>
.login {
  background: #3c485a;
  background-size: 100% 100%;
  width: 100%;
  height: 100%;
  position: fixed;
}

.login-box {
  background: #ffffff;
  border: none;
}

.login-box-msg {
  color: #000000;
  text-align: center;
}

.login-box .title {
  color: #000000;
  text-align: center;
}
</style>

<script>
export default {
  name: "Login",
  data() {
    // 账户验证
    var validateAcc = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('账号不能为空'));
      }
      if (value.length >= 16 || value.length < 4 ){
        callback(new Error('账号格式存在问题'));
      }
    };
    // 密码验证
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('密码不能为空'));
      }
      if (value.length >= 16){
        callback(new Error('密码格式存在问题'));
      }
    };
    return {
      registerFormVisible :false ,
      registerForModal : false ,
      formLabelWidth: '80px',
      registerForm: {
        userName: '',
        password: ''
      },
      userForm: {
        userName: '',
        password: ''
      },
      rules:{
        userName:[
          { validator: validateAcc, trigger: 'blur' },
        ],
        password:[
          { validator: validatePass, trigger: 'blur'},
        ]
      }
    };
  },
  methods: {

    judgeLogin(formName){
      let isSuccess = true;
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          isSuccess = !isSuccess;
          return false;
        }
      });
      if(isSuccess){this.login();}
    },
    judgeRegister(formName){
      let isSuccess = true;
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          isSuccess = !isSuccess;
          return false;
        }
      });
      if(isSuccess){this.register();}
    },

    store: function(name, form){
      window.sessionStorage.setItem("user", JSON.stringify(form));
    },

    login: async function () {
      let data = "";
      // 将账号信息封装
      var param = new FormData();
      param.append("account", this.userForm.userName);
      param.append("password", this.userForm.password);
      await this.$http.post("/api/account/login", param)
        .then(function (response) {
          data = response.data;
        });
      if (data){
        // 1. 将登录成功之后的 token，保存到客户端的 sessionStorage 中
        //   1.1 项目中出了登录之外的其他API接口，必须在登录之后才能访问
        //   1.2 token 只应在当前网站打开期间生效，所以将 token 保存在 sessionStorage 中
        this.store("user",this.userForm);
        this.initialAccount(this, this.userForm.userName, this.userForm.password);
        this.$router.push("/");
      } else{
        // 如果登入有问题，则执行下面的处理
      }
    },

    register: async function () {
      let data = "";
      // 将账号信息封装
      var param = new FormData();
      param.append("account", this.registerForm.userName);
      param.append("password", this.registerForm.password);
      await this.$http.post("/api/account/register", param)
              .then(function (response) {
                data = response.data;
              });
      if (data){
        // 1. 将注册成功之后的 token，保存到客户端的 sessionStorage 中
        //   1.1 项目中出了登录之外的其他API接口，必须在登录之后才能访问
        //   1.2 token 只应在当前网站打开期间生效，所以将 token 保存在 sessionStorage 中
        this.store("user", this.registerForm);
        this.$router.push("/");
      } else{
        // 如果登入有问题，则执行下面的处理

      }
    },

    initialAccount : function (win, userName, password) {
      let param = new FormData();
      param.append("account", userName);
      param.append("password", password);
      win.$http.post("/api/account/obtain/init", param).then(function (response) {
        if (response.data !== null){
          // alert(response.data.longitude + " " + response.data.latitude + " " + response.data.detail);
          let inform = {
            longitude : response.data.longitude,
            latitude : response.data.latitude,
            detail : response.data.detail,
            licenseKey : response.data.licenseKey
          };
          window.sessionStorage.setItem("userInform", JSON.stringify(inform));
          win.$message.success("获取账户信息成功");
        } else{
          // 如果登入有问题，则执行下面的处理
          win.$message.error("获取账户信息失败");
        }
      });
    }

  }
};
</script>
